package com.example.yskjproject.view.dialog;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.AppCompatCheckBox;
import androidx.appcompat.widget.AppCompatEditText;
import androidx.appcompat.widget.AppCompatTextView;

import com.example.yskjproject.R;
import com.example.yskjproject.content.EventContent;
import com.example.yskjproject.event.EventMessage;
import com.example.yskjproject.http.Urls;
import com.example.yskjproject.http.callback.JsonCallback;
import com.example.yskjproject.model.LoginModel;
import com.example.yskjproject.model.LzyResponse;
import com.example.yskjproject.utils.EventBusUtil;
import com.example.yskjproject.utils.SpCashUtils;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.tencent.qcloud.tuicore.util.ToastUtil;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * LoginWxDialogHelper
 * <p>
 * 作者：zx
 * 创建时间：2024/4/23
 */
public class LoginWxDialogHelper extends Dialog {

    private AppCompatEditText editPhone,edCode;
    private AppCompatCheckBox loginCheckbox;

    private AppCompatTextView phoneCodeTv;

    private CountDownTimer countDownTimer;
    private Gson gson = new Gson();
    public LoginWxDialogHelper(@NonNull Context context) {
        super(context);
        setContentView(R.layout.login_dialog2);

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Window window = getWindow();
        if (window != null) {
            WindowManager.LayoutParams layoutParams = window.getAttributes();
            layoutParams.width = (int) (getContext().getResources().getDisplayMetrics().widthPixels * 0.8); // 设置宽度为500dp
            layoutParams.height = (int) (getContext().getResources().getDisplayMetrics().heightPixels * 0.28); // 设置高度为300dp
            window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
            window.setAttributes(layoutParams);
        }
        editPhone = findViewById(R.id.ed_phone);
        edCode = findViewById(R.id.ed_code);
        loginCheckbox = findViewById(R.id.login_checkbox);
        phoneCodeTv = findViewById(R.id.phone_code_tv);
        //获取手机验证码
        phoneCodeTv .setOnClickListener(code -> {
            if (TextUtils.isEmpty(editPhone.getText().toString().trim())) {
                ToastUtil.toastShortMessage("请输入手机号!");
                return;
            }
            if (editPhone.getText().toString().length() < 10) {
                ToastUtil.toastShortMessage("请输入正确的手机号!");
                return;
            }

            OkGo.<LzyResponse>get(Urls.YZM_CODE + "?mobile=" + editPhone.getText().toString().trim() + "&type=" + 1).execute(new JsonCallback<LzyResponse>() {
                @Override
                public void onSuccess(Response<LzyResponse> response) {
                    if (TextUtils.equals("ok", response.body().msg)) {
                        ToastUtil.toastShortMessage("获取手机验证码成功!");
                        countDownTimer = new CountDownTimer(60000, 1000) {
                            @SuppressLint("SetTextI18n")
                            public void onTick(long millisUntilFinished) {
                                phoneCodeTv.setText(millisUntilFinished / 1000 + "s");
                            }

                            public void onFinish() {
                                phoneCodeTv.setText("获取验证码");
                            }
                        }.start();
                    } else {
                        ToastUtil.toastShortMessage( "获取手机验证码失败!");
                    }
                }

                @Override
                public void onError(Response<LzyResponse> response) {
                    super.onError(response);
                    ToastUtil.toastShortMessage(response.message());
                }
            });
        });


        findViewById(R.id.btn_login).setOnClickListener(login -> {
            if (TextUtils.isEmpty(editPhone.getText().toString().trim())) {
                ToastUtil.toastShortMessage("请输入手机号!");
                return;
            }

            if (TextUtils.isEmpty(edCode.getText().toString().trim())) {
                ToastUtil.toastShortMessage("请输入验证码!");
                return;
            }

            if (!loginCheckbox.isChecked()) {
                ToastUtil.toastShortMessage("请勾选同意事项!");
                return;
            }

            Map<String, String> jsonParams = new HashMap<>();
            jsonParams.put("mobile", editPhone.getText().toString().trim());
            jsonParams.put("code", edCode.getText().toString().trim());
            jsonParams.put("ticket", SpCashUtils.getInstance().getTicket());
            jsonParams.put("device_token", SpCashUtils.getInstance().getDeviceToken());
            String paramsDate = gson.toJson(jsonParams);
            RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), paramsDate);
            OkGo.<LzyResponse<LoginModel>>post(Urls.YZM_LOGIN).upRequestBody(requestBody).execute(new JsonCallback<LzyResponse<LoginModel>>() {
                @Override
                public void onSuccess(Response<LzyResponse<LoginModel>> response) {
                    LoginModel loginModel = response.body().data;
                    if (loginModel != null) {
                        SpCashUtils.getInstance().setToken(loginModel.getAccess_token());
//                        SpCashUtils.getInstance().setCurrentTokenTime(new SimpleDateFormat("yyyy-MM-dd").format(Calendar.getInstance()));
                        SpCashUtils.getInstance().setTokenTime(loginModel.getRefresh_after());
                        EventBusUtil.sendEvent(new EventMessage(EventContent.Login_Update));
                        dismiss();
                    }else{
                        ToastUtil.toastShortMessage("登录数据返回为null");
                    }
                }

                @Override
                public void onError(Response<LzyResponse<LoginModel>> response) {
                    super.onError(response);
                    ToastUtil.toastShortMessage(gson.toJson(response));
                }
            });
        });
    }


    @Override
    public void dismiss() {
        super.dismiss();
        if (countDownTimer != null) {
            countDownTimer.cancel();
            countDownTimer = null;
        }
    }
}
